package service

import (
	"go.uber.org/zap/buffer"
	"google.golang.org/protobuf/proto"
	"log"
	"strings"
	"yunque-message-client/driver"
	"yunque-message-client/model/ProtoModel"
)

/**
 * @Description
 * @Author yichen
 * @Date 2023/9/24 0024 11:06
 **/
type Message struct {
	name string
}

func NewMessage() *Message {
	//v = New()
	return &Message{}
}
func (*Message) Send(sendAct ProtoModel.SendActProto, data []byte) error {
	toData := &buffer.Buffer{}
	toData.WriteByte(byte(ProtoModel.SendTypeProto_MESSAGE.Number()))
	toData.WriteByte(byte(sendAct))
	toData.Write(data)
	driverType := getDriverType()
	err := driver.NewDriver().SendTo(driverType, "message", toData.Bytes())
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

/*
 * 推送消息给指定用户 批量
 */
func (this *Message) SendTos(uids []string, msgs []*ProtoModel.MessageProto) error {
	msgbody := &ProtoModel.MessagesPubProto{}
	msgbody.Uid = strings.Join(uids, ",")
	for _, msg := range msgs {
		msgbody.Msg = append(msgbody.Msg, msg)
	}
	data, err := proto.Marshal(msgbody)
	if err != nil {
		// 格式化失败
		log.Println(err)
		return err
	}
	return this.Send(ProtoModel.SendActProto_SENDUIDS, data)
}

/*
 * 推送消息给指定多个用户
 * 多个uid 逗号分割
 * params $uids=uid1,uid2,uid3
 */
func (this *Message) SendToUid(uid string, msgs []*ProtoModel.MessageProto) error {
	msgbody := &ProtoModel.MessagesPubProto{}
	msgbody.Uid = uid
	for _, msg := range msgs {
		msgbody.Msg = append(msgbody.Msg, msg)
	}
	data, err := proto.Marshal(msgbody)
	if err != nil {
		// 格式化失败
		log.Println(err)
		return err
	}
	return this.Send(ProtoModel.SendActProto_SENDUID, data)

}

/*
 * 批量推送消息给指定用户的某个设备
 */
func (this *Message) SendToDid(uid string, did string, msgs []*ProtoModel.MessageProto) error {

	msgbody := &ProtoModel.MessagesPubProto{}
	msgbody.Uid = uid
	msgbody.Did = did
	for _, msg := range msgs {
		msgbody.Msg = append(msgbody.Msg, msg)
	}

	data, err := proto.Marshal(msgbody)
	if err != nil {
		// 格式化失败
		log.Println(err)
		return err
	}
	return this.Send(ProtoModel.SendActProto_SENDUIDDID, data)
}

/*
 * 推送消息给所有人
 * @params $msg =MessageProto
 */
func (this *Message) SendToAll(msgs []*ProtoModel.MessageProto) error {

	msgbody := &ProtoModel.MessagesPubProto{}

	for _, msg := range msgs {
		msgbody.Msg = append(msgbody.Msg, msg)
	}
	data, err := proto.Marshal(msgbody)
	if err != nil {
		// 格式化失败
		log.Println(err)
		return err
	}
	return this.Send(ProtoModel.SendActProto_SENDALL, data)
}

/*
 * 遍历消息推给接收人
 * @params $msg =[MessageProto]
 */
func (this *Message) SendList(msgs []*ProtoModel.MessageProto) error {
	msgbody := &ProtoModel.MessagesPubProto{}

	for _, msg := range msgs {
		msgbody.Msg = append(msgbody.Msg, msg)
	}
	data, err := proto.Marshal(msgbody)
	if err != nil {
		// 格式化失败
		log.Println(err)
		return err
	}
	return this.Send(ProtoModel.SendActProto_SENDLIST, data)
}
